<?php

namespace pmvc\io;

use Exception;

class IOUtil {

	public static function openFile($filename, $mode, $useIncludePath = FALSE, $context=NULL) {
		return ($context!=NULL)
			? new ResourceStream(fopen($filename, $mode, $useIncludePath, $context))
			: new ResourceStream(fopen($filename, $mode, $useIncludePath));
	}

	public static function openSocket($host, $port=-1, &$errn, &$errstr, $timeout=NULL) {
		return ($timeout!=NULL)
			? new ResourceStream(fsockopen($host, $port, $errn, $errstr, $timeout))
			: new ResourceStream(fsockopen($host, $port, $errn, $errstr));
	}

	public static function openPipe($command, $mode) {
		return new ResourceStream(popen($command, $mode));
	}

	public static function openFilter($filename, $mode, $readFilters=NULL, $writeFilters=NULL, $dualFilters=NULL) {
		$url = "php://filter";
		if ($readFilters!=NULL) {
			$url .= "/read=".implode("|", $readFilters);
		}
		if ($writeFilters!=NULL) {
			$url .= "/write=".implode("|", $readFilters);
		}
		if ($dualFilters!=NULL) {
			$url .= "/".implode("|", $readFilters);
		}
		$url .= "/resource=".$filename;
		return new ResourceStream(fopen($url, $mode));
	}

	public static function openMemory($mode, $max=-1) {
		return ($max==-1)
			? new ResourceStream(fopen("php://memory", $mode))
			: new ResourceStream(fopen("php://temp/maxmemory:".$max, $mode));
	}

}


?>